from typing import List
from .model import Shipto
from ninja import Field, ModelSchema, Query, Router
from ninja.pagination import paginate
from utils.fu_crud import (
    ImportSchema,
    create,
    delete,
    export_data,
    import_data,
    retrieve,
    update,
)
from utils.fu_ninja import FuFilters, MyPagination

router = Router()


# 设置过滤字段
class Filters(FuFilters):
        
    contact_number: str = Field(None, alias='contact_number')    
    contact_person: str = Field(None, alias='contact_person')    
    ship_to_address: str = Field(None, alias='ship_to_address')    
    ship_id: str = Field(None, alias='ship_id')    
    partner_id: str = Field(None, alias='partner_id')


# 设置请求接收字段
class ShiptoSchemaIn(ModelSchema):

    class Config:
        model = Shipto
        model_exclude = ['create_datetime', 'update_datetime', 'belong_dept', 'modifier', 'creator', 'id']


# 设置响应字段
class ShiptoSchemaOut(ModelSchema):

    class Config:
        model = Shipto
        model_fields = '__all__'


# 创建Shipto
@router.post('/shipto', response=ShiptoSchemaOut)
def create_shipto(request, data: ShiptoSchemaIn):
    shipto = create(request, data, Shipto)
    return shipto


# 删除Shipto
@router.delete('/shipto/{id}')
def delete_shipto(request, id: int):
    delete(id, Shipto)
    return {'success': True}


# 更新Shipto
@router.put('/shipto/{id}', response=ShiptoSchemaOut)
def update_shipto(request, id: int, data: ShiptoSchemaIn):
    shipto = update(request, id, data, Shipto)
    return shipto


# 获取Shipto
@router.get('/shipto', response=List[ShiptoSchemaOut])
@paginate(MyPagination)
def list_shipto(request, filters: Filters = Query(...)):
    qs = retrieve(request, Shipto, filters)
    return qs


# 导入
@router.get('/shipto/all/export')
def export_shipto(request):
    export_fields = ('contact_number', 'contact_person', 'ship_to_address', 'ship_id', 'partner_id', )
    return export_data(request, Shipto, ShiptoSchemaOut, export_fields)


# 导出
@router.post('/shipto/all/import')
def import_shipto(request, data: ImportSchema):
    import_fields = ('contact_number', 'contact_person', 'ship_to_address', 'ship_id', 'partner_id', )
    return import_data(request, Shipto, ShiptoSchemaIn, data, import_fields)
    